package com.whiteape.book.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.whiteape.book.R;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReplaceRuleManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.ReplaceRuleBean;
import com.whiteape.book.model.type.LoadFileType;
import com.whiteape.book.ui.adapter.ReplaceRuleAdapter;
import com.whiteape.book.ui.base.BaseActivity;
import com.whiteape.book.ui.dialog.InputDialog;
import com.whiteape.book.ui.dialog.ReplaceRuleDialog;
import com.whiteape.book.utils.BitIntentDataManager;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.widget.itemdecoration.DividerItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.whiteape.book.core.manager.ReplaceRuleManager.getInstance;

public class ReplaceRuleActivity extends BaseActivity {

    @BindView(R.id.rv_text_filter)
    RecyclerView recyclerView;

    //    private CollectionMediaBean collectionMediaBean;
    private String title;
    private String siteHostUrl;
    private List<ReplaceRuleBean> data = new ArrayList<>();
    private ReplaceRuleAdapter adapter;
    private boolean allSelected = false;
    private final int REQUEST_CODE_LOCAL_FILE = 1112;
    private static final String KEY_TITLE = "key_title";
    private static final String KEY_SITE_HOST_URL = "key_site_host_url";

    public static void startThisForResult(Activity context, int requestCode, String title, String siteHostUrl) {
//        String key = String.valueOf(System.currentTimeMillis());
        Intent intent = new Intent(context, ReplaceRuleActivity.class);
//        BitIntentDataManager.getInstance().putData(key, collectionMediaBean);
        intent.putExtra(KEY_TITLE, title);
        intent.putExtra(KEY_SITE_HOST_URL, siteHostUrl);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
//        String dataKey = getIntent().getStringExtra("data_key");
//        if (!TextUtils.isEmpty(dataKey)) {
//            collectionMediaBean = (CollectionMediaBean) BitIntentDataManager.getInstance().getData(dataKey);
//        }
        title = getIntent().getStringExtra(KEY_TITLE);
        siteHostUrl = getIntent().getStringExtra(KEY_SITE_HOST_URL);
        adapter = new ReplaceRuleAdapter(R.layout.item_replace_rule, data);
        super.initData(savedInstanceState);
    }

    @Override
    protected void initView() {
        super.initView();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this));
        recyclerView.setAdapter(adapter);

    }

    @Override
    protected void initEvent() {
        super.initEvent();

        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if (view.getId() == R.id.iv_edit) {
                editReplaceRule(data.get(position));
            } else if (view.getId() == R.id.iv_del) {
                ReplaceRuleManager.getInstance().deleteReplaceRule(data.get(position));
            } else if (view.getId() == R.id.tv_replace_rule) {

                data.get(position).setEnable(!data.get(position).getEnable());
                ReplaceRuleManager.getInstance().insertReplaceRule(data.get(position));
            }
            startLogic();
        });
    }

    @Override
    protected void startLogic() {
        super.startLogic();
        addDisposable(ReplaceRuleManager.getInstance().getAllReplaceRules().subscribe(replaceRuleBeans -> {
            data.clear();
            data.addAll(replaceRuleBeans);
            adapter.notifyDataSetChanged();
            upDateSelectAll();
        }));

    }

    @Override
    protected int getContentId() {
        return R.layout.activity_text_filter;
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);

        if (null != getSupportActionBar()) {
            getSupportActionBar().setTitle("净化规则");
        }
        toolbar.setNavigationOnClickListener(v -> {
                    setResult(RESULT_OK);
                    finish();
                }
        );
    }
    public void upDateSelectAll() {
        allSelected = true;
        for (ReplaceRuleBean replaceRuleBean : data) {
            if (replaceRuleBean.getEnable() == null || !replaceRuleBean.getEnable()) {
                allSelected = false;
                break;
            }
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(RESULT_OK);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_text_filter, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void editReplaceRule(ReplaceRuleBean replaceRuleBean) {
        ReplaceRuleDialog.builder(this, replaceRuleBean, title, siteHostUrl)
                .setPositiveButton(replaceRuleBean1 -> {
                    addDisposable(ReplaceRuleManager.getInstance().insertReplaceRuleByRx(replaceRuleBean1)
                            .subscribe(ret -> {
                                startLogic();
                            }));
                }).show();
    }

    private void selectAll() {
        allSelected = !allSelected;
        for (ReplaceRuleBean replaceRuleBean : data) {
            replaceRuleBean.setEnable(allSelected);
        }
        adapter.notifyDataSetChanged();
        ReplaceRuleManager.getInstance().insertReplaceRuleList(data);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_add:
                editReplaceRule(null);
                break;
            case R.id.action_select_all:
                selectAll();
                break;
            case R.id.action_import_by_net:
                InputDialog.builder(this)
                        .setTitle(getString(R.string.input_replace_url))
                        .setAdapterValues(new String[]{""})
                        .setCallback(inputText -> {
                            inputText = StringUtils.trim(inputText);
                            addDisposable(ReplaceRuleManager.getInstance().importReplaceRuleByUrl(inputText).subscribe(ret -> {
                                if (ret > 0) {
                                    ToastUtils.show("导入成功");
                                } else {
                                    ToastUtils.show("导入失败，请检查导入链接格式是否正确");
                                }
                            }));
                        }).show();
                break;
            case R.id.action_import_by_local:
                Intent intent = new Intent(this, FileSystemActivity.class);
                intent.putExtra(FileSystemActivity.FILE_TYPE_KEY, LoadFileType.FILE_TYPE_REPLACE_RULE);
//
                startActivityForResult(intent, REQUEST_CODE_LOCAL_FILE);
                break;
            case R.id.action_export:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE_LOCAL_FILE) {
            List<File> fileList = (List<File>) data.getSerializableExtra("data");
            if (fileList == null) {
                finish();
                return;
            }
            addDisposable(ReplaceRuleManager.getInstance().importReplaceRule(fileList).subscribe(ret -> {
                if (ret > 0) {
                    ToastUtils.show("导入成功");
                } else {
                    ToastUtils.show("导入失败，请检查导入链接格式是否正确");
                }
            }));


        }
    }
}
